package com.ruoyi.web.controller.vantController.orderController;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.AliyunSmsUtils;
import com.ruoyi.common.utils.ResultMap;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.MoneyPercentage;
import com.ruoyi.system.domain.WithdrawDeposit;
import com.ruoyi.system.domain.customer.CustomerLogin;
import com.ruoyi.system.domain.customer.PayableInstalment;
import com.ruoyi.system.domain.zhuangxiumain.orderformMain.OrderDetail;
import com.ruoyi.system.domain.zhuangxiumain.orderformMain.OrderMaster;
import com.ruoyi.system.domain.zhuangxiumain.orderformMain.OrderVoucher;
import com.ruoyi.system.domain.zhuangxiumain.shopMain.SupplierInfo;
import com.ruoyi.system.domain.zhuangxiumain.vo.AfterSaleVo;
import com.ruoyi.system.domain.zhuangxiumain.vo.OrderVo;
import com.ruoyi.system.domain.zhuangxiumain.vo.ZhiFuVo;
import com.ruoyi.system.service.IMoneyPercentageService;
import com.ruoyi.system.service.IWithdrawDepositService;
import com.ruoyi.system.service.vantservice.orderservice.ApiOrderDetailService;
import com.ruoyi.system.service.vantservice.orderservice.ApiOrderMasterService;
import com.ruoyi.system.service.vantservice.orderservice.ApiOrderVoucherService;
import com.ruoyi.system.service.zhaungxiuservice.shopService.SupplierInfoService;
import com.ruoyi.system.utils.TokenUtils;
import com.ruoyi.web.controller.payment.WxPayController;
import io.swagger.models.auth.In;
import javafx.scene.web.WebView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * Created by 惠普 on 2020/12/24 10:08
 */
@RestController
@RequestMapping("/api/order/master")
@CrossOrigin
public class ApiOrderMasterController extends BaseController {

    @Autowired
    private ApiOrderMasterService apiOrderMasterService;

    @Autowired
    private ApiOrderDetailService apiOrderDetailService;

    @Autowired
    private ApiOrderVoucherService apiOrderVoucherService;

    @Autowired
    private WxPayController wxPayController;

    @Autowired
    private TokenUtils tokenUtils;

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private IWithdrawDepositService withdrawDepositService;
    @Autowired
    private IMoneyPercentageService moneyPercentageService;
    @Autowired
    private SupplierInfoService supplierInfoService;
    @Value("${ruoyi.telphone}")
    private String telPhone;
    /**
     * 订单售后查询
     * @param afterSaleVo
     * @return
     */
    @PostMapping(value = "/afterSaleVoList")
    public AjaxResult selectAfterSaleVoList(@RequestBody AfterSaleVo afterSaleVo){
        try {
            // 获取前台登录用户信息
            CustomerLogin customerLogin = tokenUtils.getLoginCustomer(request);
            afterSaleVo.setCustomerId(customerLogin.getCustomerId());
            return AjaxResult.success(apiOrderMasterService.selectAfterSaleVoList(afterSaleVo));
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("发生错误");
        }
    }

    /**
     * 订单列表信息
     * @param orderVo
     * @return
     */
    @PostMapping("/orderVoList")
    public AjaxResult selectOrderVoList(@RequestBody OrderVo orderVo){
        try {
            // 获取前台登录用户信息
            CustomerLogin customerLogin = tokenUtils.getLoginCustomer(request);
            orderVo.setCustomerId(customerLogin.getCustomerId());
            return AjaxResult.success(apiOrderMasterService.selectOrderVoList(orderVo));
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("发生错误");
        }
    }

    /**
     * 修改订单状态操作
     * @param orderVo
     * @return
     */
    @PostMapping("/cancelOrderVo")
    public AjaxResult cancelOrderVo(@RequestBody OrderVo orderVo){
        try {
            System.out.println(orderVo);
            System.out.println("************************"+orderVo.getOrderStatus());
            System.out.println("**************"+orderVo.getSupplierId());
            if (orderVo.getOrderStatus()== 4) {
                System.out.println("**************************我进来提现了****************************");
                WithdrawDeposit wd = new WithdrawDeposit();
                SupplierInfo supplierInfo = supplierInfoService.selectSupplierInfoById((int)orderVo.getSupplierId());
                supplierInfo.getSupplierCode();     //获取商家的唯一标识
                WithdrawDeposit withdrawDeposit = withdrawDepositService.selectWithdrawDepositById(Integer.parseInt( supplierInfo.getSupplierCode()));  //根据code码查询到绑定的订单表
                MoneyPercentage moneyPercentage = moneyPercentageService.selectMoneyPercentageById(1);
                wd.setDepositShouyi(withdrawDeposit.getDepositShouyi()+orderVo.getPaymentMoney());     //传入金额
                wd.setDepositKetixian(withdrawDeposit.getMoneynumber()+orderVo.getPaymentMoney()-((withdrawDeposit.getMoneynumber()+orderVo.getPaymentMoney())*moneyPercentage.getPercent()));
                wd.setMoneynumber(withdrawDeposit.getMoneynumber()+orderVo.getPaymentMoney());
                wd.setCode(supplierInfo.getSupplierCode());
                System.out.println("********************************************"+wd);
                withdrawDepositService.updateWithdrawDeposit(wd);
                return AjaxResult.success(apiOrderMasterService.updateOrderVo(orderVo));
            }
            return AjaxResult.success(apiOrderMasterService.updateOrderVo(orderVo));
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("发生错误");
        }
    }

    /**
     * 订单预支付
     * @param orderMaster
     * @return
     */
    @PostMapping("/insertOrderMaster")
    public AjaxResult insertOrderMaster(@RequestBody OrderMaster orderMaster){
        apiOrderMasterService.insertOrderMaster(orderMaster);
        return AjaxResult.success(orderMaster.getOrderId());
    }

    /**
     * 订单详情
     * @param orderDetail
     * @return
     */
    @PostMapping("/insertOrderDetail")
    public AjaxResult insertOrderDetail(@RequestBody OrderDetail orderDetail){
        return AjaxResult.success(apiOrderDetailService.insertOrderDetail(orderDetail));
    }

    /**
     * 修改订单支付方式
     * @param orderMaster
     * @return
     */
    @PostMapping("/updateOrderMethod")
    public AjaxResult updateOrderMethod(@RequestBody OrderMaster orderMaster){
        StringBuilder stringBuilder = new StringBuilder();
        Random random = new Random();
        for (int i=0;i<8;i++){
            stringBuilder.append(random.nextInt(10));
        }
        String num =stringBuilder.toString();
        System.err.println("**********88888888888888"+num);
//        OrderMaster orderShoppingCode = apiOrderMasterService.getOrderShoppingCode(orderMaster);
//        System.out.println("----------------------------------------------------------"+orderShoppingCode);
//        WithdrawDeposit wd = new WithdrawDeposit();
//        wd.setCode(orderShoppingCode.getSupplier_code());   //添加codes码
//        WithdrawDeposit withdrawDeposit = withdrawDepositService.selectWithdrawDepositById(Integer.parseInt(wd.getCode()));  //根据code码查询到绑定的订单表
//        wd.setDepositShouyi(withdrawDeposit.getDepositShouyi()+orderMaster.getPaymentMoney());     //传入金额
//        MoneyPercentage moneyPercentage = moneyPercentageService.selectMoneyPercentageById(1);
//        wd.setDepositKetixian(withdrawDeposit.getMoneynumber()+orderMaster.getPaymentMoney()-((withdrawDeposit.getMoneynumber()+orderMaster.getPaymentMoney())*moneyPercentage.getPercent()));
//        wd.setMoneynumber(withdrawDeposit.getMoneynumber()+orderMaster.getPaymentMoney());
//        withdrawDepositService.updateWithdrawDeposit(wd);
        orderMaster.setOrderSn(num);
        return AjaxResult.success(apiOrderMasterService.updateOrderMethod(orderMaster));
    }

    @PostMapping("/updateOrderMethodtwo")
    public AjaxResult updateOrderMethodtwo(@RequestBody OrderMaster orderMaster){

        StringBuilder stringBuilder = new StringBuilder();
        Random random = new Random();
        for (int i=0;i<8;i++){
            stringBuilder.append(random.nextInt(10));
        }
        String num =stringBuilder.toString();
        OrderMaster orderShoppingCode = apiOrderMasterService.getOrderShoppingCode(orderMaster);

        return AjaxResult.success(apiOrderMasterService.updateOrderMethod(orderMaster));
    }

    /**
     * 上传订单凭证
     * @param file
     * @return
     */
    @PostMapping("/uploadVoucher")
    public AjaxResult uploadVoucher(@RequestParam("voucherFile") MultipartFile file) throws IOException {
        if (!file.isEmpty())
        {
            AjaxResult ajaxResult = AjaxResult.success();
            String avatar = FileUploadUtils.upload(RuoYiConfig.getVoucherPath(), file);
            ajaxResult.put("img",avatar);
            return ajaxResult;
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }

    @PostMapping("/uploadVoucherTwo")
    public Map<String, Object> uploadVoucherTwo(@RequestParam("file") MultipartFile[] file) {
        Map<String, Object> resultMap = apiOrderVoucherService.uploadPingzheng(file);
//        OrderVoucher orderVoucher = new OrderVoucher();
//            orderVoucher.setOrderMasterId(orderId);
//            orderVoucher.setOrderVoucherUrl("http://51jhf.com/profile/"+ resultMap.get("img0"));
//            apiOrderVoucherService.insertOrderVoucher(orderVoucher);
//            resultMap.put("orderVoucherId", orderVoucher.getOrderVoucherId());
        return resultMap;
    }


    /**
     * 修改订单支付方式
     * @param orderVoucher
     * @return
     */
    @PostMapping("/insertOrderVoucher")
    public AjaxResult insertOrderVoucher(@RequestBody OrderVoucher orderVoucher){
        int count = apiOrderVoucherService.insertOrderVoucher(orderVoucher);
        if(count>0){
            // 创建短信验证码类对象
            AliyunSmsUtils smsUtils = new AliyunSmsUtils();
            try {
                //发送短信
                SendSmsResponse response = smsUtils.sendSms(telPhone, "123456");
            } catch (ClientException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return AjaxResult.success(count);
    }

    /**
     * 全部订单中去付款的线下支付方法
     * @param orderVo
     * @return
     */
    @PostMapping("/updateOrderVoThree")
    public AjaxResult updateOrderVoThree(@RequestBody OrderVo orderVo){
        int row = apiOrderMasterService.updateOrderVoThree(orderVo);
        if(row == 1){
            return AjaxResult.success("支付成功");
        }else {
            return AjaxResult.error("支付失败");
        }
    }


}
